<template>
    <page>
        <group gutter="0" class="mt-1">
            <cell title="应付金额"><span class="text f24">￥{{应付金额}}</span></cell>
            <cell-form-preview :list="应付金额列表"></cell-form-preview>
        </group>
        <group>
            <cell title="优惠总金额"><span class="text f24">￥{{优惠总金额}}</span></cell>
            <cell-form-preview :list="优惠总金额列表"></cell-form-preview>
            <cell title="优惠券" is-link @click.native="优惠券列表 && 优惠券列表.length && (couponShow = true)">
                <span v-if="优惠券列表.length == 0">没有可用优惠券</span>
                <template v-else>
                    <span class="orange mr5" v-if="优惠券">{{优惠券.freeMoney / 100}}元</span>
                    <span class="fsm">{{优惠券 ? `(${优惠券.title})`: '不使用优惠券'}}</span>
                </template>
                <span v-else>
                    没有可用优惠券
                </span>
            </cell>
        </group>
        <m-button class="mt40 mx12" @click.native="submit" :class="{disabled: this.form.payMoney <= 0}">
            实际支付：{{this.form.payMoney / 100}}元
        </m-button>
        <p class="h30 c1 f14 tc" v-if="this.form.payMoney <= 0">此金额不支持支付</p>
        <!-- 选择优惠券弹窗 begin-->
        <div v-transfer-dom>
            <popup v-model="couponShow" style="height: 75%">
                <section class="fill ofay bg-main1">
                    <div class="h44 px16 white-bg" flex="main:justify cross:center"
                         @click="优惠券 = null;couponShow = false">
                        不使用优惠券
                        <i class="iconfont icon-selected equal f22 c1" v-if="优惠券 == null"></i>
                        <i class="iconfont icon-unselected equal f22 text" v-else></i>
                    </div>
                    <coupon-item v-for="(i, index) in 优惠券列表" :key="index"
                                 :data="i" class="mx12 mb10 mycoupon rel"
                                 @click.native="优惠券 = i;couponShow = false">
                        <i class="iconfont icon-selected equal check-icon c1" v-if="i == 优惠券"></i>
                        <i class="iconfont icon-unselected equal check-icon text" v-else></i>
                    </coupon-item>
                </section>
            </popup>
        </div>
        <!-- 选择优惠券弹窗 end-->
    </page>
</template>
<script>
  import oils from '@/utils/油品'
  import couponItem from '@/pages/优惠券/_item'
  import { getBrandWCPayRequest } from '@/common/jssdk'
  import urljoin from 'url-join'
  import { closePop } from '@/utils/tiny'

  export default {
    data () {
      // 默认 gunId 线上支付, 如有 oilGunStateId 则为线下对接支付
      const {shopId, oilCode, gunCode, payMoney, oilNumber, gunId, oilGunStateId, price, publicPrice} = this.$route.params
      return {
        couponShow: false,
        baseForm: {
          shopId, oilCode, gunCode, payMoney, oilNumber, gunId, oilGunStateId, price, publicPrice
        },
        会员组优惠: null,
        专车优惠: null,
        优惠券: null,
        优惠券列表: []
      }
    },
    created () {
      this.PitsPullData()
    },
    computed: {
      /*---- 展示列表(金额以元为单位)  begin-----*/
      应付金额 () {
        return this.baseForm.payMoney / 100
      },
      应付金额列表 () {
        const {oilCode, gunCode, oilNumber, price} = this.baseForm
        const 油枪号 = {label: '油枪号', value: gunCode}
        const 油品 = {label: '油品', value: oils.getByCode(oilCode).code}
        const 油量 = {label: '油量', value: `${oilNumber}升`}
        const 油品价格 = {label: '油品价格', value: price / 100 + '元'}
        return [油枪号, 油品, 油量, 油品价格]
      },
      优惠总金额 () {
        return this.form.couponTotle / 100
      },
      优惠总金额列表 () {
        const {memberRuleMoney, carRuleMoney} = this.form
        const 会员优惠 = {label: '会员优惠', value: memberRuleMoney / 100 + '元'}
        const 专车优惠 = {label: '专车优惠', value: carRuleMoney / 100 + '元'}
        // const 门店直减 = {label: '门店直减', value: 0}
        return [会员优惠, 专车优惠]
      },
      /*---- 展示列表(金额以元为单位) end-----*/


      // 处理给后台的表单 (金额以分为单位)
      form () {
        /*
        *  后台金额以分为单位
        * */
        const {shopId, oilCode, gunCode, payMoney, oilNumber, gunId, oilGunStateId} = this.baseForm
        const $default = {id: 0, freeMoney: 0}
        const {id: carRuleId, freeMoney: carRuleMoney} = this.专车优惠 || $default
        const {id: memberRuleId, freeMoney: memberRuleMoney} = this.会员组优惠 || $default
        const {id: couponId, freeMoney: couponMoney} = this.优惠券 || {id: 0, freeMoney: 0} || $default

        const 总优惠 = carRuleMoney + memberRuleMoney + couponMoney
        return {
          oilGunStateId, gunId, // 线下对接接口 oilGunStateId or gunId
          shopId, gunCode, payMoney, oilNumber,
          oilCode: oils.getByCode(oilCode).code, // 油品号
          oilspend: payMoney, // 油品金额
          commodityspend: 0, // 非油金额 (这里没有非油品)
          total: payMoney, // 油品金额 + 非油金额 (这里没有非油品)
          carRuleId,
          carRuleMoney,
          memberRuleId,
          memberRuleMoney,
          couponId,
          couponMoney,
          couponTotle: 总优惠, // 优惠总额
          payMoney: payMoney - 总优惠, // 实际支付金额(结算后金额)
        }
      },
      // 处理后表单
      PitsPushData () {
        const {carRuleMoney, memberRuleMoney, couponMoney, payMoney, couponTotle, total, oilspend} = this.form
        return {
          ...this.form,
          carRuleMoney: parseInt(carRuleMoney),
          memberRuleMoney: parseInt(memberRuleMoney),
          couponMoney: parseInt(couponMoney),
          payMoney: parseInt(payMoney),
          couponTotle: parseInt(couponTotle),
          total: parseInt(total),
          oilspend: parseInt(oilspend)
        }
      }
    },
    methods: {
      // 处理优惠券表单
      PitsCouponForm () {
        const {payMoney, oilCode, shopId} = this.PitsPushData
        return {
          payMoney,
          oilCode: oils.getByCode(oilCode).end,
          shopId
        }
      },
      // 过滤，排序，取最大 优惠券，优惠规则等等
      async PitsPullData () {
        /*----------------------------- 获取可用优惠券列表, 会员优惠规则列表,专车规则列表 --------------------------------------*/
        let discountCoupon = this.$get_loading('coupon/getUseableCoupon', {oilCode: oils.getByCode(this.oilCode).end, ...this.PitsCouponForm()})
        let preferentialRules = this.$get_loading('coupon/getUserablePreferentialRuleByUserId')
        discountCoupon = await discountCoupon
        preferentialRules = await preferentialRules
        /*-------------------------------------------------------------------*/
        const 优惠券列表 = discountCoupon.obj || []
        const 优惠规则 = preferentialRules.obj || []

        const 优惠券 = 优惠券列表.sort((a, b) => b.freeMoney - a.freeMoney)[0]
        //console.log(优惠券)

        const 会员组优惠 = 优惠规则
          .filter(x => x.corwd == 1 && this.baseForm.payMoney > x.minSpend)
          .sort((a, b) => b.freeMoney - a.freeMoney)[0]

        const 专车优惠 = 优惠规则
          .filter(x => x.corwd == 2 && this.baseForm.payMoney > x.minSpend)
          .sort((a, b) => b.freeMoney - a.freeMoney)[0]

        Object.assign(this, {优惠券, 会员组优惠, 专车优惠, 优惠券列表})
        //console.log(优惠券列表, 会员组优惠, 专车优惠)
      },
      async submit () {
        try {
          // 如果传了 oilGunStateId 就判断为线下支付
          const url = isEmpty(this.baseForm.oilGunStateId) ? 'shift/addShiftDetail' : 'shift/addShiftDetail2'
          let {obj: id} = await this.$post_loading(url, this.PitsPushData) // 获取订单 id
          const {obj: config} = await this.$post_loading('pay/fasGetOil', {id}) // 通过订单 id 获取 签名

          // 确认后台收到付款, 每0.5秒查询一次， 查询10次
          const getState = async () => {
            const body = await this.$get('shift/getShiftDetailById', {id})
            console.log(body)
            return body.obj.state
          }

          getBrandWCPayRequest(config, getState).then(() => {
            // 支付成功
            this.$store.dispatch('updateUserInfo')
            this.$router.push({name: 'refueling_success', query: {id}})
          }).catch((e) => {
            // 支付失败
            this.$router.push({
              name: 'refueling_fail', params: {
                description: e == 'cancel' ? '支付被取消' : JSON.stringify(e)
              }
            })
            throw e
          })
        } catch (e) {
          // 支付失败
          e == 'cancel' && m_toast('订单被终止')
          throw e
        }
      },
      closePop () {
        return closePop(this, 'couponShow')
      }
    },
    beforeRouteLeave (to, from, next) {
      next(this.closePop())
    },
    components: {
      couponItem
    }
  }
</script>
<style type="text/scss" lang="scss" scoped>
    @import '../../css/variable';

    .mycoupon {
        border: 2px solid transparent;
    }

    .check-icon {
        $size: 22px;
        position: absolute;
        font-size: $size;
        top: 50%;
        right: 15px;
        margin-top: -$size/2;
    }
</style>
